//
//  XWXSqliteTableTool.m
//  XWXSqlite
//
//  Created by 许卫星 on 17/9/8.
//  Copyright © 2017年 wxxu. All rights reserved.
//

#import "XWXSqliteTableTool.h"
#import "XWXSqliteQueryCommand+Table.h"
#import "XWXSqliteTable.h"
#import "XWXSqliteModelTool.h"

@implementation XWXSqliteTableTool

/**
 判断表格是否已经存在(注意容错大小写)
 */
+ (BOOL)isTableExistsWithModelClass: (Class)cls withDBName: (NSString *)dbName
{
    NSString *tableName = [XWXSqliteModelTool tableNameWithModelClass:cls];
    XWXSqliteQueryCommand *queryCommand = [[XWXSqliteQueryCommand alloc] initWithDatabaseName:dbName];
    [queryCommand isTableExists:tableName];
    
    NSError *error;
    NSArray <NSDictionary *>*resultSet = [XWXSqliteTable fetchWithSQL:queryCommand.sqlString withDBName:dbName error:&error];
    
    __block BOOL isTableExists = NO;
    [resultSet enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([[obj[@"name"] lowercaseString] isEqualToString:[tableName lowercaseString]]) {
            isTableExists = YES;
        }
    }];
    return isTableExists;
    
}

/**
 获取表格里面所有的字段,排序后
 拿到创建表格的语句，截取括号中的字段
 */
+ (NSMutableArray *)tableAllColumnWithModelClass: (Class)cls withDBName: (NSString *)dbName
{
    NSString *tableName = [XWXSqliteModelTool tableNameWithModelClass:cls];
    XWXSqliteQueryCommand *queryCommand = [[XWXSqliteQueryCommand alloc] initWithDatabaseName:dbName];
    [queryCommand tableAllColumnNames:tableName];
    
    NSError *error;
    NSArray *resultSet = [XWXSqliteTable fetchWithSQL:queryCommand.sqlString withDBName:dbName error:&error];
    NSString *createSql = resultSet.firstObject[@"sql"];
    
    //CREATE TABLE xxx(age integer,num integer,score real,name text,xxx text, primary key(num))
    NSArray *sqlArray = [createSql componentsSeparatedByString:@"("];
    if (sqlArray.count >= 2) {
        // age integer,num integer,score real,name text,xxx text, primary key
        NSString *columnStr = sqlArray[1];
        NSArray *columnNameTypeArray = [columnStr componentsSeparatedByString:@","];
        
        NSMutableArray *columnNames = [NSMutableArray array];
        for (NSString *columnNameType in columnNameTypeArray) {
            if ([columnNameType containsString:@"primary"]) {
                continue;
            }
            //            age integer
            // 去除首尾空格, 并按空格进行划分
            NSString *columnName = [[columnNameType stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsSeparatedByString:@" "].firstObject;
            [columnNames addObject:columnName];
        }
        
        columnNames = (NSMutableArray *)[columnNames sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            return [obj1 compare:obj2];
        }];

        return columnNames;
    }
    return nil;
}
    
/**
 判断表格是否需要更新
 // 字段个数不一致, 大小写不一致, 均判定为需要更新
 // 目的是为了跟模型的所有字段保持一致
 //  name ->  nAMe  nAmE
 */
+ (BOOL)isRequireUpdate:(Class)cls withDBName:(NSString *)tableName
{
    // 需要更新的情况 删除字段, 增加字段, 改名
    // 1. 现获取, 所有的已经存在的表格内, 的字段, 组成的数组(old)
    NSArray *tableColumnNames = [self tableAllColumnWithModelClass:cls withDBName:tableName];
    
    // 2. 获取模型, 应该被创建成为表结构的, 所有字段 (new)
    NSArray *modelColumnNames = [XWXSqliteModelTool allTableSortedIvarNames:cls];
    
    BOOL isUpdate = ![tableColumnNames isEqualToArray:modelColumnNames];

    return isUpdate;
}

@end
